package com.crr.service.impl;

import com.crr.bean.Dept;
import com.crr.common.crud.BaseServiceImpl;
import com.crr.mapper.DeptMapper;
import com.crr.query.DeptQuery;
import com.crr.service.DeptService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public  class DeptServiceImpl extends BaseServiceImpl<Dept, DeptMapper> implements DeptService {
    @Override
    public List<Map> queryChildDept(DeptQuery query) {
        return baseMapper.queryChildDept(query);
    }

    @Override
    public List<Map> queryTree() {
        return baseMapper.queryTree(0);
    }

    public int save(Dept entity){
       entity.setDeptCode(generateDeptCode(entity.getParentId()));
       return super.save(entity);
   }
public int delete(Serializable id){
       int num=baseMapper.countChildDept(id);
       if(num>=1){
            return 2;//说明有子部门，不允许删除
       }
       return super.delete(id);
}
    /**
     * 生成编码
     * @param parentId
     * @return
     */
    String generateDeptCode(int parentId) {
        String maxCode= baseMapper.queryMaxDeptCode(parentId);
        if(null==maxCode){
            //说明父部门里还没有子部门
            if(parentId==0)
                //说明添加的是顶级部门
                return "101";
            //根据父id找父code
            String parentCode= baseMapper.queryCodeById(parentId);
           return parentCode+"01";
        }
        //如果已经存在子部门
        Integer tag=Integer.parseInt(maxCode);
        tag++;
        return String.valueOf(tag);
    }

    @Override
    public int updateStatus(int id, int status) {
      return   baseMapper.updateStatus(id,status);
    }
}
